#!/usr/bin/env python
# -*- coding: utf-8 -*-
from string import Template
from datetime import datetime
from tack.lib import json_app, content_headers, status_codes
from tack_ocie.api.util import sql_string, sql_int, sql_unstring

## SQL statements below

select_one = """
SELECT * 
FROM ocie_report
WHERE report_id = $report_id AND active = 1
"""


def get(environ, start_response):
    try:
        report_id = environ['dispatcher.groups']['report_id']
        sql = Template(select_one).substitute(locals())
        cursor = environ['connection'].cursor()
        cursor.execute(sql)
        rows = cursor.fetchall()
        if rows:
            output = {}
            output['title'] = rows[0].title
            output['name'] = rows[0].title + '.pdf'
            form = environ['form']
            sql = sql_unstring(rows[0].query)
            sql = replaceWithDictValues(sql, form)
            cursor = environ['connection'].cursor()
            cursor.execute(sql)
            rows = cursor.fetchall()
            output['sections'] = []
            subsection = {}
            subsection['title'] = ''
            subsection['table'] = {}
            subsection['table']['headers'] = makeColumnList(cursor.description)
            subsection['table']['rows'] = []
            for row in rows:
                subsection['table']['rows'].append(makeDataList(cursor.description, row))
            output['sections'].append(subsection)
        else:
            start_response(status_codes.not_found, content_headers.default_plain())
            return ['404 Not Found']
    except:
        output = {}
        output['title'] = 'Report Error'
        output['name'] = 'Report Error.pdf'
        output['sections'] = []
        subsection = {}
        subsection['title'] = ''
        subsection['table'] = {}
        subsection['table']['headers'] = ['Report Error']
        subsection['table']['rows'] = [['This report would not run: ' + sql]]
        output['sections'].append(subsection)
    return json_app(output)(environ, start_response)


def replaceWithDictValues(sql, form):
    for k, v in form.iteritems():
        v = sql_string(v)
        sql = sql.replace(k, v)
    return sql


def makeColumnList(cd):
    column_list = []
    for column in cd:
        column_list.append(column[0])
    return column_list


def makeDataList(cd, row):
    value_list = []
    for i, c in enumerate(row):
        if cd[i][1] == datetime:
            row[i] = row[i].strftime('%Y-%m-%d %H:%M') if row[i] else None
        value_list.append(row[i])
    return value_list